package pfq.demo.gson;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

/**
 * Created by pangfuqiang on 2018/2/24.
 */

public class BooleanJsonAdapter extends TypeAdapter<Person> {
    @Override
    public void write(JsonWriter out, Person value) throws IOException {
        out.beginObject();
        out.name("name").value(value.getName());
        out.name("age").value(value.getAge());
        out.name("isMale").value(value.isMale());
        out.endObject();
    }

    @Override
    public Person read(JsonReader in) throws IOException {
        Person person = new Person();
        in.beginObject();
        while (in.hasNext()) {
            switch (in.nextName()) {
                case "name":
                    person.setName(in.nextString());
                    break;
                case "age":
                    person.setAge(in.nextInt());
                    break;
                case "isMale":
                    person.setMale(in.nextInt() != 0);
                    break;
                case "avatar_url":
                    person.setAvatarUrl(in.nextString());
                    break;
            }
        }
        in.endObject();
        return person;
    }

}
